package xyz.qduwo.servlet;

import org.hibernate.Hibernate;
import org.hibernate.LobHelper;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import xyz.qduwo.dao.CanvasDao;
import xyz.qduwo.dao.UserDao;
import xyz.qduwo.entity.CanvasEntity;
import xyz.qduwo.entity.UserEntity;
import xyz.qduwo.util.EncryptUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.util.Date;

@WebServlet(name = "canvasServlet", urlPatterns = { "/canvasServlet" })
public class CanvasServlet extends HttpServlet {
    private byte[] InputStreamToByte(ServletInputStream is) throws IOException {

        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();

        return imgdata;
    }
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        //得到session
        Configuration cfg = new Configuration().configure();
        ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        SessionFactory sf = cfg.buildSessionFactory(sr);
        Session sess = sf.openSession();
        //得到LobHelper
        LobHelper lobHelper = sess.getLobHelper();
        try (ServletInputStream sis = request.getInputStream()) {
            UserEntity userEntity=(UserEntity)session.getAttribute("userentity");
            CanvasEntity canvasEntity = new CanvasEntity();
            //TODO: 将图片以文件形式保存在文件系统中
            canvasEntity.setImage("");
            canvasEntity.setOwner(userEntity.getId());
            canvasEntity.setCreateDate(new java.sql.Date(new Date().getTime()));
            new CanvasDao().save(canvasEntity);
            System.out.println("Finish");

        }catch (Exception e){
            System.out.println(e.getMessage());
        }

    }
}
